package com.srlg.batch.user;

import com.srlg.batch.model.entity.User;
import org.springframework.batch.item.database.JdbcBatchItemWriter;
import org.springframework.batch.item.database.builder.JdbcBatchItemWriterBuilder;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

import javax.sql.DataSource;

@Configuration
public class UserCmpConfig {

    // 读
    @Bean
    public FlatFileItemReader<User> userFlatFileItemReader() {
        return new FlatFileItemReaderBuilder<User>()
                .name("userItemReader")
                .resource(new ClassPathResource("data.csv"))
                .linesToSkip(1)
                .delimited()
                .names("姓名", "性别", "年龄", "地址")
                .fieldSetMapper(new UserFieldSetMapper()).build();
    }

    // 执行
    @Bean
    public UserItemProcessor processor() {
        return new UserItemProcessor();
    }

    // 写
    @Bean
    public JdbcBatchItemWriter<User> userJdbcBatchItemWriter(DataSource dataSource) {
        return new JdbcBatchItemWriterBuilder<User>()
                .sql("INSERT INTO t_user (name, sex, age, address, status) VALUES (:name, :sex, :age, :address, :status)")
                .dataSource(dataSource)
                .beanMapped()
                .build();
    }
}
